<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/3/23
 * Time: 22:45
 */

namespace App\Services;


use App\Facades\Amap;
use App\Models\District;
use App\Models\OwnerRoutes;
use Illuminate\Database\Eloquent\Model;

class RouteService extends BaseService
{
    /**
     * 新增路由信息
     * @param $ownerUuid 货主唯一ID
     * @param $srcLocation 出发地 经纬度
     * @param $dstLocation 目的地 经纬度
     * @param $srcAddress 出发地
     * @param $dstAddress 目的地
     * @return mixed 路由信息
     * @throws \Exception
     */
    public function addOwnerRoute($ownerUuid, $srcLocation, $dstLocation, $srcAddress, $dstAddress)
    {
        $route = OwnerRoutes::where('owner_uuid', $ownerUuid)
            ->where('src_location', $srcLocation)
            ->where('dst_location', $dstLocation)
            ->first();
        if (!empty($route)) {
            return $route->id;
        }

        // 获取经纬度对应的城市
        $srcInfo = Amap::regeo($srcLocation);
        $dstInfo = Amap::regeo($dstLocation);

        $srcDistrictCode = $srcInfo->adcode;
        $dstDistrictCode = $dstInfo->adcode;
        if (!$srcDistrictCode) {
            throw new \Exception('定位起始城市信息失败');
        }
        if (!$dstDistrictCode) {
            throw new \Exception('定位目的城市信息失败');
        }

        // 获取省份、城市、区/县 的 adcode
        $srcCity     = District::with('parent')->where('adcode', $srcDistrictCode)
            ->first()->toArray();
        $srcProvince = District::with('parent')->where('adcode', $srcCity['parent']['adcode'])
            ->first()->toArray();

        $dstCity     = District::with('parent')->where('adcode', $dstDistrictCode)
            ->first()->toArray();
        $dstProvince = District::with('parent')->where('adcode', $dstCity['parent']['adcode'])
            ->first()->toArray();

        // 保存数据
        $data['owner_uuid']        = $ownerUuid;
        $data['src_province_code'] = $srcProvince['parent']['adcode'];
        $data['src_city_code']     = $srcProvince['adcode'];
        $data['src_district_code'] = $srcDistrictCode;
        $data['src_location']      = $srcLocation;
        $data['src_address']       = $srcAddress;
        $data['dst_province_code'] = $dstProvince['parent']['adcode'];
        $data['dst_city_code']     = $dstProvince['adcode'];
        $data['dst_district_code'] = $dstDistrictCode;
        $data['dst_location']      = $dstLocation;
        $data['dst_address']       = $dstAddress;
        // 驾驶距离
        $data['driving_distance'] = Amap::distance($srcLocation, $dstLocation, 1)[0]->distance;
        // 直线距离
        $data['line_distance'] = Amap::distance($srcLocation, $dstLocation, 0)[0]->distance;

        $route = OwnerRoutes::create($data);

        return $route->id;
    }

    /**
     * 获取收发货的详细地址，如[云南省昆明市东川区xx村xx组xx号, 湖南省濮阳市台前县xx村xx组xx号]
     * @param $routeId
     * @param Model $model
     * @param array $srcDep 取值级别：1取省，2取市，3取区，4取详细地址
     * @param array $dstDep 取值级别：1取省，2取市，3取区，4取详细地址
     * @return array
     */
    public function getDetailedAddressByRouteId($routeId, Model $model, $srcDep = [1, 2, 3, 4], $dstDep = [1, 2, 3, 4])
    {
        try {
            if (!$routeId || !is_object($model)) {
                throw new \Exception('参数非法');
            }

            $srcDetail = $dstDetail = '';

            $oRoute       = $model::where('id', $routeId)->firstOrFail();
            $containerSrc = [];
            in_array(1, $srcDep) && array_push($containerSrc, $oRoute->src_province_code);
            in_array(2, $srcDep) && array_push($containerSrc, $oRoute->src_city_code);
            in_array(3, $srcDep) && array_push($containerSrc, $oRoute->src_district_code);

            $containerDst = [];
            in_array(1, $dstDep) && array_push($containerDst, $oRoute->dst_province_code);
            in_array(2, $dstDep) && array_push($containerDst, $oRoute->dst_city_code);
            in_array(3, $dstDep) && array_push($containerDst, $oRoute->dst_district_code);

            $src = (new District())->getNameByAdcode($containerSrc);
            if (sizeof($src)) {
                $srcDetail = join('', array_filter(array_values($src)));
            }
            in_array(4, $srcDep) && $srcDetail .= $oRoute->src_address;

            $dst = (new District())->getNameByAdcode($containerDst);
            if (sizeof($dst)) {
                $dstDetail = join('', array_filter(array_values($dst)));
            }
            in_array(4, $dstDep) && $dstDetail .= $oRoute->dst_address;

            // 距离
            if (isset($oRoute->driving_distance)) {
                $distance = $oRoute->driving_distance;
                return compact('srcDetail', 'dstDetail', 'distance');
            } else {
                return compact('srcDetail', 'dstDetail');
            }
        } catch (\Exception $e) {
            return [];
        }
    }
}